<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="enterobj.name" clearable placeholder="请输入内容" class="search-main" @clear="search" />
      <el-button type="primary" @click="search">查询</el-button>
    </div>
    <div class="create-container">
      <el-button v-permission="'park:enterprise:add_edit'" type="primary" @click="$router.push('/park/addenterprise')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" stripe @expand-change="expandChange">
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.zhankailist">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime">
                <template #default="zhankaiobj">
                  {{ zhankaiobj.row.startTime }}--{{ zhankaiobj.row.endTime }}
                </template>
              </el-table-column>
              <el-table-column label="合同状态" prop="status">
                <template #default="zhankaiobj">
                  <el-tag :type="statussuccess(zhankaiobj.row.status)">
                    {{ zhuangtaima(zhankaiobj.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="zhankaiobj">
                  <el-button v-permission="'park:rent:add_surrender'" size="mini" type="text" :disabled="zhankaiobj.row.status === 3" @click="tuizuenter(zhankaiobj.row.id)">退租</el-button>
                  <el-button v-permission="'park:rent:remove'" size="mini" type="text" :disabled="zhankaiobj.row.status !== 3" @click="Shanchuenter(zhankaiobj.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button v-permission="'park:rent:add_surrender'" size="mini" type="text" @click="openhetong(row.id)">添加合同</el-button>
            <el-button v-permission="'park:enterprise:query'" size="mini" type="text" @click="$router.push(`/park/detailenterprise/${row.id}`)">查看</el-button>
            <el-button v-permission="'park:enterprise:add_edit'" size="mini" type="text" @click="editenter(row.id)">编辑</el-button>
            <el-button v-permission="'park:enterprise:remove'" size="mini" type="text" @click="delenter(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 页码区域 -->
    <div class="page-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="enterobj.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加合同弹框 -->
    <el-dialog
      title="添加合同"
      :close-on-click-modal="false"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in rentbillist"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              unlink-panels
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              ref="resetupload"
              action="#"
              :http-request="httpRequest"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="onExceed"
              :on-remove="onRemove"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="addformsubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { enterpriseAPI, DeleteenterAPI, getrentbuildingAPI, AddEditenterAPI, ZhankaiEnterAPI, TuizuenterAPI, ShanchuenterAPI } from '@/api/enterprise'
import { fileuploadAPI } from '@/api/common'
// import { mapState } from 'vuex'
export default {
  name: 'EnterPrise',
  data() {
    return {
      enterobj: {
        name: '',
        page: 1,
        pageSize: 2
      },
      list: [],
      total: null,
      rentDialogVisible: false,
      rentForm: {
        buildingId: null, // 楼宇id
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称id
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentbillist: [],
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件', trigger: 'change' }
        ]
      }
    }
  },
  // computed: {
  //   ...mapState('menu', ['permission'])
  // },
  created() {
    this.enterprisegetlist()
    // console.log(123123, this.permission)
  },
  // 初始化调用接口数据
  methods: {
    async enterprisegetlist() {
      const res = await enterpriseAPI(this.enterobj)
      // console.log(res.data.rows)
      this.list = res.data.rows.map(item => {
        return {
          ...item,
          zhankailist: []
        }
      })
      this.total = res.data.total
    },
    // 展开合同详情
    async expandChange(row, expandedRows) {
      // console.log(row, expandedRows)
      const findrowid = expandedRows.find(item => item.id === row.id)
      if (!findrowid) return
      const res = await ZhankaiEnterAPI(row.id)
      // console.log(res)
      // eslint-disable-next-line require-atomic-updates
      row.zhankailist = res.data
    },
    // 退租企业合同
    tuizuenter(id) {
      // console.log(id)
      this.$confirm('你确定要退租吗', '温馨提示').then(async() => {
        await TuizuenterAPI(id)
        // console.log(res)
        this.$message.success('退租成功')
        this.enterprisegetlist()
      }).catch(() => {
        this.$message.warning('退租失败')
      })
    },
    // 删除企业合同
    Shanchuenter(id) {
      this.$confirm('你确定要删除吗', '温馨提示').then(async() => {
        await ShanchuenterAPI(id)
        // console.log(res)
        this.$message.success('删除成功')
        this.enterprisegetlist()
      }).catch(() => {
        this.$message.warning('删除失败')
      })
    },
    // 展开状态码更新
    zhuangtaima(val) {
      const status = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return status[val]
    },
    statussuccess(val) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      return MAP[val]
    },
    // 打开添加合同弹框
    async openhetong(id) {
      this.rentDialogVisible = true
      // 获取楼宇下拉列表
      const res = await getrentbuildingAPI()
      this.rentbillist = res.data
      this.rentForm.enterpriseId = id
    },
    // 上传租赁合同附件
    async httpRequest({ file }) {
      // console.log(file)
      const formdatafile = new FormData()
      formdatafile.append('file', file)
      formdatafile.append('type', 2)
      const res = await fileuploadAPI(formdatafile)
      this.rentForm.contractId = res.data.id
      this.rentForm.contractUrl = res.data.url
      this.$refs.addForm.validateField('contractId')
    },
    // 确定添加租赁合同
    addformsubmit() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          // const { buildingId, contractId, contractUrl, enterpriseId, type } = this.rentForm
          const [startTime, endTime] = this.rentForm.rentTime
          this.rentForm.startTime = startTime
          this.rentForm.endTime = endTime
          delete this.rentForm.rentTime
          await AddEditenterAPI(this.rentForm)
          this.enterprisegetlist()
          this.closeDialog()
          this.$message.success('租赁合同添加成功')
        }
      })
    },
    // 上传前的文件限制
    beforeUpload(file) {
      // console.log(file)
      const typeList = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
        'application/pdf']
      const typesize = file.size / 1024 / 1024
      if (typeList.includes(file.type) && typesize < 5) {
        return true
      } else {
        this.$message.warning('请上传符合规则的文件')
        return false
      }
    },
    // 文件移除时的钩子
    onRemove() {
      this.rentForm.contractId = this.rentForm.contractUrl = ''
      this.$refs.addForm.validateField('contractId')
    },
    // 上传文件超出限制提醒
    onExceed() {
      this.$message.warning('超出文件限制个数')
    },
    // 关闭添加合同弹框
    closeDialog() {
      this.rentDialogVisible = false
      this.$refs.addForm.resetFields()
      this.rentForm = {
        buildingId: null, // 楼宇id
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称id
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      }
      this.$refs.resetupload.clearFiles()
    },
    // 编辑企业
    editenter(id) {
      this.$router.push({
        path: '/park/addenterprise',
        query: {
          id: id
        }
      })
    },
    // 删除企业
    delenter(id) {
      this.$confirm('此操作将永久删除该企业', '是否继续?').then(async() => {
        await DeleteenterAPI(id)
        if (this.list.length === 1 && this.enterobj.page > 1) {
          this.enterobj.page--
        }
        this.$message.success('删除成功')
        this.enterprisegetlist()
        // console.log(res)
      }).catch(() => {})
    },
    // 搜索模块
    search() {
      this.enterobj.page = 1
      this.enterprisegetlist()
    },
    // 切换页码
    handleCurrentChange(val) {
      // console.log(val)
      this.enterobj.page = val
      this.enterprisegetlist()
    },
    // 序号处理
    indexMethod(index) {
      // console.log(index)
      return (this.enterobj.page - 1) * this.enterobj.pageSize + index + 1
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
